﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using NDK.Motion.Monitor;
using System.Reflection;

namespace NDK.Motion.Controls
{
    public partial class ucDebug_Var : UserControl
    {
        [Bindable(false), Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public object MonitoredObject
        {
            get; set;
        }
        public ucDebug_Var()
        {
            InitializeComponent();
        }
        private void Init()
        {
            //初始化表格的行数据
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new Action(Init));
            }
            else
            {
                if (MonitoredObject == null)
                {
                    return;
                }
                List<MonitorItem> monitorItems = GetMonitoredItems();
                foreach (var monitorItem in monitorItems)
                {
                    int index = dgv_Var.Rows.Add();
                    dgv_Var.Rows[index].Cells["cVarName"].Value = monitorItem.Name;
                    dgv_Var.Rows[index].Cells["cVarValue"].Value = monitorItem.Value;
                    dgv_Var.Rows[index].Cells["cVarDescription"].Value = monitorItem.Description;
                    dgv_Var.Rows[index].Cells["cVarType"].Value = monitorItem.VariableType;
                }
            }
        }
        private void ucDebug_CT_Load(object sender, EventArgs e)
        {
            Init();
        }

        private void ckb_Minitor_CheckedChanged(object sender, EventArgs e)
        {
            if (ckb_Minitor.Checked == true)
            {
                timer1.Start();
            }
            else
            {
                timer1.Stop();
            }
        }
        /// <summary>
        /// 控件标题
        /// </summary>
        [Browsable(true), Description("Control Name"), Category("CustomerDefine")]
        public string Title
        {
            get
            {
                return lbl_Name.Text;
            }
            set
            {
                lbl_Name.Text = value;
            }
        }
        /// <summary>
        /// 更新变量表
        /// </summary>
        private void UpdateVarTable()
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new Action(UpdateVarTable));
            }
            else
            {
                //控件被销毁，或未创建，或未传入监控对象，直接反回
                if (this.IsDisposed || !this.IsHandleCreated || MonitoredObject == null)
                {
                    return;
                }
                //获得监控对象的监控变量
                List<MonitorItem> monitorItems = GetMonitoredItems();
                //需要监控的变量数未0，直接反回
                if (monitorItems.Count == 0)
                {
                    return;
                }
                int count = dgv_Var.RowCount;
                //界面监控内容未初始化
                if (count == 0)
                {
                    Init();
                }
                else
                {
                    //更新界面的值
                    for (int i = 0; i < count; i++)
                    {
                        MonitorItem mi = monitorItems.Find(item => item.Name == dgv_Var.Rows[i].Cells["cVarName"].Value.ToString());
                        if (mi != null)
                        {
                            dgv_Var.Rows[i].Cells["cVarValue"].Value = mi.Value;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 获取监控对象的所有监控变量
        /// </summary>
        /// <returns></returns>
        private List<MonitorItem> GetMonitoredItems()
        {
            List<MonitorItem> MonitoredItemList = new List<MonitorItem>();
            bool isDefined = Attribute.IsDefined(MonitoredObject.GetType(), typeof(MonitorAttribute));
            if (isDefined == true)
            {
                //查询工站中所有需要监视的属性，添加到监视列表
                var props = MonitoredObject.GetType().GetProperties();
                foreach (var prop in props)
                {
                    var attrs = Attribute.GetCustomAttributes(prop);
                    if (prop.IsDefined(typeof(MonitorAttribute), false))
                    {
                        MonitorAttribute ma = prop.GetCustomAttribute<MonitorAttribute>();
                        MonitorItem mi = new MonitorItem();
                        if (ma.DisplayName == string.Empty)//没有手动命名，默认采用属性名
                        {
                            mi.Name = prop.Name;
                        }
                        else
                        {
                            mi.Name = ma.DisplayName;
                        }
                        mi.Value = prop.GetValue(MonitoredObject);
                        mi.VariableType = prop.PropertyType.Name;
                        if (ma.Description == string.Empty)//没有手动注释，默认为"None"
                        {
                            mi.Description = "None";
                        }
                        else
                        {
                            mi.Description = ma.Description;
                        }
                        MonitoredItemList.Add(mi);

                    }
                }
                //查询工站中所有需要监视的字段，添加到监视列表
                var fields = MonitoredObject.GetType().GetFields();
                foreach (var field in fields)
                {
                    var attrs = Attribute.GetCustomAttributes(field);
                    if (field.IsDefined(typeof(MonitorAttribute), false))
                    {
                        MonitorAttribute ma = field.GetCustomAttribute<MonitorAttribute>();
                        MonitorItem mi = new MonitorItem();
                        if (ma.DisplayName == string.Empty)//没有手动命名，默认采用字段名
                        {
                            mi.Name = field.Name;
                        }
                        else
                        {
                            mi.Name = ma.DisplayName;
                        }
                        mi.Value = field.GetValue(MonitoredObject);
                        mi.VariableType = field.FieldType.Name;
                        if (ma.Description != string.Empty)//没有手动注释，采用默认值
                        {
                            mi.Description = ma.Description;
                        }
                        MonitoredItemList.Add(mi);
                    }
                }
            }
            return MonitoredItemList;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            UpdateVarTable();
        }
    }
}
